let express = require('express');
let DB = require('../../modules/db');
let router = express.Router();
let multiparty = require('multiparty');//既可以获取数据又能上传图片
let fs = require('fs');
router.get("/",function (req,res) {
    DB.find('product',{},(err,data)=>{
        res.render('admin/product/index',{
            listGoods:data
        })
    })
})

router.get("/add",function (req,res) {

    res.render("admin/product/add");
})
router.post('/doAdd',function (req,res) {
    let form = new multiparty.Form();
    form.uploadDir = 'loadImg';//图片的路径

    form.parse(req,function (err,fields,files) {
        let title = fields.title[0];
        let price = fields.price[0];
        let fee = fields.fee[0];
        let description = fields.description[0];
        let pic = files.pic[0].path;
        DB.insert('product',{
            title,
            pic,
            price,
            fee,
            description
        },function (err,data) {

            if(!err){
                console.log("添加数据成功");
                res.redirect('/admin/product');
            }
        })
    })
})

router.get("/edit",function (req,res) {

    let id = req.query.id;
    DB.find('product',{_id:new DB.ObjectID(id)},function (error,data) {
        console.log(data[0]);
        res.render('admin/product/edit',{
            list:data[0]
        })
    })


});

router.post('/doEdit',function (req,res) {

    let form = new multiparty.Form();
    form.uploadDir = 'loadImg';

    form.parse(req,(err,fields,files)=>{
        // console.log(fields);
        console.log(files);
        let id = fields._id[0];
        let title = fields.title[0];
        let price = fields.price[0];
        let fee = fields.fee[0];
        let description = fields.description[0];
        let pic = files.pic[0].path;
        let originalFileName = files.pic[0].originalFilename;
        let setData = {};
        if(originalFileName){
            setData = {
                title,
                pic,
                price,
                fee,
                description
            }
        }else{
            //没有上传图片
            setData = {
                title,
                price,
                fee,
                description
            }
            //删除生成的临时文件
            fs.unlink(pic);
        }
        DB.update('product',{"_id":new DB.ObjectID(id)},setData,function (error,data) {
            if(!error){
                res.redirect('/admin/product');
                console.log("数据修改成功");
            }
        })
    })
})
router.get("/delete",function (req,res) {

    let id = req.query.id;
    console.log(id);
    DB.delete('product',{"_id":new DB.ObjectID(id)},function (err) {
        if(!err){
            res.redirect("/admin/product");
        }
    });
})

module.exports = router; //暴露路由模块